import socket
from cStringIO import StringIO

class aswhois:
	"""whois search for AS"""
	server = 'whois.apnic.net'
	def set_server(self, server):
		self.server = server
	def search(self, asn):
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.connect((self.server, 43))
		s.send("AS" + asn + "\r\n")
		response = ''
		self.aut_num = ''
		self.as_name = ''
		self.descr = ''
		self.country = ''
		while True:
			d = s.recv(4096)
			response += d
			if d == '':
				break
		s.close()
		string = StringIO(response)
		inasblock = False
		descr = ''
		for line in string:
			if line.find('aut-num') == -1 and inasblock == False:
				continue
			elif line.find('aut-num') != -1:
				self.aut_num = line.split(':')[1].strip()
				inasblock = True
				continue
			elif inasblock:
				if line.find('as-name') != -1:
					self.as_name = line.split(':')[1].strip()
					continue
				if line.find('descr') != -1:
					descr += line.split(':')[1].strip() + " "
					continue
				if line.find('country') != -1:
					self.descr = descr
					self.country = line.split(':')[1].strip()
					break
